package com.guagua.chat.room;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import com.guagua.vas.util.CacheManager;

/**
 * 作者:白云鹏 E-mail:yunpeng@17guagua.com
 * 创建时间：Jul 2, 2012 12:00:02 PM
 * 类说明
 */
public class ChatRoomUtil {
	/**
	 * 密钥
	 */
	public static final String key="gg%*!_^$%ll)fav";
	
	/**
	 * 域
	 */
	private static String FIELD="zy.17guagua.com";

	public static final String ACTIVETOROOMKEY="ACTIVETOROOM";
	
	/**
	 * 活动列表集合缓存KEY
	 * @param room_id 房间ID
	 * @return key
	 */	
	public static String ROOMACTIVE_ROOM_ID(long room_id){
		return "ROOMACTIVE_"+room_id;
	};
	/**
	 * 从缓存中获取房间信息
	 * @param room_id 房间ID
	 * @return key
	 */	
	public static String ROOMINFO_ROOM_ID(long room_id){
		return "ROOMINFO_"+room_id;
	};

	/**
	 * 从缓存中获取房间第一页明星列表信息
	 * @param room_id 房间ID
	 * @return key
	 */	
	public static String ROOMSINGER_ROOM_ID(long room_id){
		return "ROOMSINGER_"+room_id;
	};
	/**
	 * 从缓存中获取房间拍好顺序前4个明星列表信息
	 * @param room_id 房间ID
	 * @return key
	 */	
	public static String ROOMSINGER_4_ROOM_ID(long room_id){
		return "ROOMSINGER_4_"+room_id;
	};
	/**
	 * 缓存明星刷新时间
	 * @param room_id 房间ID
	 * @return key
	 */	
	public static String TIMEUNIT_ROOMSTAR_ROOM_ID(long room_id){
		return "TIMEUNIT_ROOMSTAR_"+room_id;
	};
	/**
	 * 缓存明星等级图片
	 * @param room_id 房间ID
	 * @return key
	 */	
	public static String LEVELICON_ROOM_ID(long room_id,int isListStarPage){
		return "LEVELICON_"+room_id+"_"+isListStarPage;
	};
	/**
	 * 缓存明星等级图片
	 * @param room_id 房间ID
	 * @return key
	 */	
	public static String LEVELUSERS_ROOM_ID(long roomid){
		return "LEVELUSERS_ROOM_ID"+roomid;
	};
	public static void removeLEVELICON_ROOM_ID(long room_id){
//		CacheManager.getInstance().remove(ChatRoomUtil.LEVELICON_ROOM_ID(room_id,0));
		CacheManager.getInstance().remove(ChatRoomUtil.LEVELICON_ROOM_ID(room_id,1));
	}
	/**
	 * 从缓存中读取LIST 获取房主有哪些房间
	 * @param room_id 房间ID
	 * @return key
	 */	
	public static String USERROOM_USER_ID(long user_id){
		return "USERROOM_USER_ID"+user_id;
	};
	
	/**
	 * 从缓存中读取LIST 验证用户是否登录过房间
	 * @param room_id 房间ID
	 * @return key
	 */	
	public static String CHECK_LOGIN_ROOM_INFO(long uid){
		return "CHECK_LOGIN_ROOM_INFO"+uid;
	};
	
	
	/**
	 * 验证用户是否登录过此房间。
	 * @param uid 用户ID
	 * @param roomid	房间ID
	 * @return true登录过，false没有登录过。
	 */
	public static boolean checkLoginRoomInfo(long uid,long roomid){
		List<Long> list = (List<Long>)CacheManager.getInstance().get(CHECK_LOGIN_ROOM_INFO(uid));
		if(null==list || list.size()==0){
			return false;
		}
		if(list.contains(roomid)){
			return true;
		}
		return false;
	}
	
	/**
	 * 向当天用户房间登录信息中添加信息。
	 *  用来验证当天每个房间每个用户是否访问过。
	 *  每天晚上12点自动除去失效。
	 * @param uid	用户ID
	 * @param roomid	房间ID
	 */
	public static void putLoginRoomInfo(long uid,long roomid){
		String key=CHECK_LOGIN_ROOM_INFO(uid);
		List<Long> list = (List<Long>)CacheManager.getInstance().get(key);
		if(null==list){
			list = new ArrayList<Long>();
		}
		list.add(roomid);
		CacheManager.getInstance().put(key, list,getTimeUnitMillisecond(), TimeUnit.MILLISECONDS);
	}
	

	public static void putObj(String key,Object obj){
		CacheManager.getInstance().put(key, obj,getTimeUnitMillisecond(), TimeUnit.MILLISECONDS);
	}
	public static Object getObj(String key){
		return CacheManager.getInstance().get(key);
	}
	public static void removeObj(String key){
		CacheManager.getInstance().remove(key);
	}
	
	/**
	 * 获取当前时间距离今天12点的时间差
	 */
	public static Long getTimeUnitMillisecond(){
		Long subtime = (long)0;
		Long currTimeLong = System.currentTimeMillis();
		Calendar c=Calendar.getInstance();
		String currTimeString = c.get(Calendar.YEAR)+ "-"+(c.get(Calendar.MONTH)+1) + "-" + c.get(Calendar.DATE);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		Long time12;
		try {
			time12 = sdf.parse(currTimeString + " 23:59:59").getTime();
		} catch (ParseException e) {
			return (long)0;
		}
		subtime = time12 - currTimeLong;
		return subtime;		
	} 
	
	/**
	 * 检测当前时间与传进来的时间 相差是否为指定的时间
	 * @param time 传进来的时间
	 * @param tu 指定的时间类型，天，小时，分还是秒
	 * @param tuValue 指定值，1天。2天10 小时，30分钟 等等
	 * @return 如果当前时间与指定时间相同相差指定值时，则返回TRUE，否则FALSE
	 */
	public static boolean checkTimeGTCurrTimeHowTime(long time,TimeUnit tu,long tuValue){
		boolean res = false;
		long tempTimeC = System.currentTimeMillis() - time;//获取当前时间与传进来的时间差
		if(tu == TimeUnit.DAYS){//天
			tuValue = tuValue*24*60*60*1000;
		}else if(tu == TimeUnit.HOURS){//小时
			tuValue = tuValue*60*60*1000;
		}else if(tu == TimeUnit.MILLISECONDS){//毫秒
			
		}else if(tu == TimeUnit.MINUTES){//秒
			tuValue = tuValue*1000;
		}else if(tu == TimeUnit.SECONDS){//分
			tuValue = tuValue*60*1000;
		}
		if(tempTimeC>tuValue){
			res = true;
		}
		return res;
	}
	
	/**
	 * 获取年+月
	 * yyyy+op+mm
	 * @param op
	 * @return
	 */
	public static String getCurrYearMonth(String op){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy"+op+"MM"); 
//		System.out.println(sdf.format(new Date()));
		return sdf.format(new Date());
	}
	
	/**
	 * 获取最大多少页
	 * @param pageSize 每页显示多少条
	 * @param tolPage  一共多少条
	 * @return
	 */
	public static int getMaxPage(int pageSize,int tolPage){
		int t = 0;
		if(tolPage%pageSize!=0){t=1;}
		return tolPage/pageSize + t;
	}
	
	
	/**
	 * byte转为str
	 * @param digest 字节数组
	 * @return 字节转化为字符串后的结果
	 */
	private static String bytetoString(byte[] digest) {  
		   String str = "";  
		   String tempStr = "";  
		   for (int i = 1; i < digest.length; i++) {   
		    tempStr = (Integer.toHexString(digest[i] & 0xff));   
		    if (tempStr.length() == 1) {    
		     str = str + "0" + tempStr;   
		    }else {    
		     str = str + tempStr;   
		    }  
		   }  
		   return str.toLowerCase(); 
	}
	/**
	 * str转为MD5后的str，对字符串进行MD5加密
	 * @param str 需要进行MD5加密的字符串
	 * @return MD5加密后的字符串
	 */
	public static String strMD5(String str){
		//MD5是16位,SHA是20位（这是两种报文摘要的算法）
		MessageDigest me=null;
		try{
			//md5算法
			me=MessageDigest.getInstance("MD5");
			me.update(str.getBytes());
		}
		catch(Exception e){
			e.printStackTrace();
		}
		//返回MD5串
		return bytetoString(me.digest());
	}
	/** 
     * MD5 加密 
     */   
   private String getMD5Str(String str) {   
        MessageDigest messageDigest = null;   
  
       try {   
            messageDigest = MessageDigest.getInstance("MD5");   
  
            messageDigest.reset();   
  
            messageDigest.update(str.getBytes("UTF-8"));   
        } catch (NoSuchAlgorithmException e) {   
            System.out.println("NoSuchAlgorithmException caught!");   
            System.exit(-1);   
        } catch (UnsupportedEncodingException e) {    
            e.printStackTrace();   
        }   
  
       byte[] byteArray = messageDigest.digest();   
  
        StringBuffer md5StrBuff = new StringBuffer();   
  
       for (int i = 0; i < byteArray.length; i++) {               
           if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)   
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));   
           else   
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));   
        }   
  
       return md5StrBuff.toString().toLowerCase();   
    } 
    /**
     * 返回字符串包含英文 一共多少个字节。
     * @param str
     * @param len
     * @return
     */
	public static String returnStrByLen(String str,int len){
		int tempLen = 0;
		String tempString = "";
		for(char c : str.toCharArray()){
			if(checkCN(c+"")){
				tempLen=tempLen+2;
			}else{
				tempLen=tempLen+1;
			}
			if(tempLen>len){
				break;
			}
			tempString+=c;
		}
		if(tempLen>len){
			return tempString+"...";
		}else{
			return tempString;
		}
	}
	/**
	 * 获取两个时间相差多长时间
	 * @return
	 */
	public static String getEndTimeCompareStarTime(long endTime,long starTime){
		long t = endTime - starTime;
		String result = "";
		long tt = 1000;//1秒
		float tempResult = 0;
		if(t>tt){
			tt = 60*1000;
			if(t>tt){//大于1分钟
				tt = 1000*60*60;
				if(t>tt){//大于1小时
					tt = 1000*60*60*24;//1天
					if(t>tt){//大于1天
						tempResult = (float)t/1000/60/60/24;
						result = tempResult+"天";
					}else{
						tempResult =(float)t/1000/60/60;
						if(tempResult==24){
							result = "1天";
						}else{
							result = tempResult+"小时";
						}
					}
				}else{
					tempResult = (float)t/1000/60;
					if(tempResult==60){
						result = "1小时";
					}else{
						result = tempResult+"分";
					}
				}
			}else{
				tempResult = (float)t/1000;
				if(tempResult==60){
					result = "1分";
				}else{
					result = tempResult+"秒";
				}
			}
		}else{
			tempResult = (float)t;
			if(tempResult==1000){
				result = "1秒";
			}else{
				result = tempResult+"毫秒";
			}
		}
		result=result.replace(".0", "");		
		return result;
	}
	/**
	 * 判断传进来的字符串是否是中文
	 * @param tString
	 * @return
	 */
	private static boolean checkCN (String tString){
		Pattern pattern = Pattern.compile("^[\u4e00-\u9fa5]");
		Matcher matcher = pattern.matcher(tString);
		if (matcher.find()) {
			return true;
		}
		return false;
	}
	 // 短日期格式
	 public static String DATE_FORMAT = "yyyy-MM-dd";
	 
	 // 长日期格式
	 public static String TIME_FORMAT = "yyyy-MM-dd HH:mm";


	 /**
	  * 将日期格式的字符串转换为长整型
	  * 
	  * @param date
	  * @param format
	  * @return
	  */
	 public static long convertTimeToLong(String date, String format) {
	  try {
	   if (StringUtils.isNotBlank(date)) {
	    if (StringUtils.isBlank(format))
	     format = TIME_FORMAT;

	    SimpleDateFormat sf = new SimpleDateFormat(format);
	    return sf.parse(date).getTime();
	   }
	  } catch (ParseException e) {
	   e.printStackTrace();
	  }
	  return 0l;
	 }


}
